﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Fuse8.ContentManagementFramework.DataAccess.Contents;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.ContentManagementFramework.BizFacade.Services.Contents
{
    public class FrontEndContentProvider<TEntity> : IContentProvider<TEntity> where TEntity : class, IContentItem, IEntityObject<int>, new()
    {
        private static Dictionary<Type, bool>  dataAccessSet = new Dictionary<Type, bool>();
        private static IEntityBusinessService<TEntity, int> service;

        protected static IEntityBusinessService<TEntity, int> Service
        {
            get { return service ?? (service = new BusinessServiceFacade<TEntity, int>()); }
        }

        public IEnumerable<TEntity> FindAll(Expression<Func<TEntity, object>> selector)
        {
            EnsureDataAccess();
            return selector != null ? Service.FindAll(selector) : Service.FindAll();
        }

        private void EnsureDataAccess()
        {
            var key = typeof(TEntity);
            if (!dataAccessSet.ContainsKey(key))
            {
                ContentItemDataAccessPolicy.Register<TEntity>();
                dataAccessSet[key] = true;
            }
        }

        public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, object>> selector)
        {
            EnsureDataAccess();
            return selector != null ? Service.Find(expression, selector) : Service.Find(expression);
        }

        public TEntity FindOne(int id)
        {
            EnsureDataAccess();
            return Service.FindOne(p => p.PublicContentId == id);
        }

        public TEntity FindOne(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, object>> selector)
        {
            EnsureDataAccess();
            return selector != null ? Service.FindOne(expression, selector):Service.FindOne(expression);
        }
    }
}